from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
from django.core.cache import cache
from django.core.serializers import serialize

from ...utils.users import get_login_user_id, rand_num_file
from ...utils.time_conversion import iso_to_times
from ...models.chat_file_upload import ChatFiles
from ...models.users import Users

from django.utils import timezone
from datetime import timedelta


import json, os, datetime
# from datetime import datetime


def upload_file(request):
    '''
    上传文件
    POST
    res = {
        "name": "(1).jpg",
        "obj_key": "./static/upload/2024/7/1720665761541415.jpg",
        "size": 29818,
        "url": "/static/upload/2024/7/1720665761541415.jpg",
        "ext": ".jpg"
    }
    '''
    if request.method == 'POST':
        get_params = request.GET.dict()

        if request.FILES:
            # 获取用户id
            userid = get_login_user_id(request, isadmin=False)
            # 获取上传的文件 以及一些需要的信息
            uploaded_file = request.FILES['file']
            uploaded_file_name = uploaded_file.name
            uploaded_file_size = uploaded_file.size
            uploaded_file_ext = "." + uploaded_file_name.split('.')[-1]

            time_path = "uploads/" + datetime.datetime.now().strftime("%Y/%m/%d")

            # 创建保存文件的实例
            fs = FileSystemStorage()

            # 创建保存文件的基础路径
            os.makedirs(os.path.join(fs.location, time_path), exist_ok=True)

            # 随机生成16位数字文件名称
            rand_file_name = rand_num_file(uploaded_file_ext)

            # 获取保存文件的路径
            file_path = os.path.join(time_path, rand_file_name)

            # 保存文件
            try:
                filename = fs.save(file_path, uploaded_file)
            except:
                res_mes = {
                    "code": 1,
                    "message": "文件保存失败！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)

            visit_url = fs.url(filename)

            # 判断上传的文件 是否是头像文件
            if get_params:
                # 是头像
                is_avatar = True
            else:
                # 不是头像
                is_avatar = False

            # 创建数据库信息
            try:
                ChatFiles.objects.create(
                    user_id = userid,
                    name = uploaded_file_name,
                    obj_key = visit_url,
                    url = visit_url,
                    ext = uploaded_file_ext,
                    size = uploaded_file_size,
                    img = file_path,
                    avatar = is_avatar,
                )
            except:
                res_mes = {
                    "code": 1,
                    "message": "文件信息保存失败！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            
            # 更新用户头像数据库
            if get_params:
                Users.objects.filter(id=userid).update(avatar=visit_url)

                # 更新redis的缓存
                # 先看看redis有没有缓存，有的话 再更新
                user_cache_mes = cache.get(f'user_info_{userid}')
                if user_cache_mes:
                    user_cache_mes['avatar'] = visit_url
                    cache.set(f'user_info_{userid}', user_cache_mes, timeout=3600)

            # 返回数据
            res_mes = {
                "code": 0,
                "data": {
                    "ext": uploaded_file_ext,
                    "name": uploaded_file_name,
                    "obj_key": visit_url,
                    "size": uploaded_file_size,
                    "url": visit_url
                }
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)


def upload_list(request):
    '''
    获取全部文件
    '''
    # 获取用户id
    userid = get_login_user_id(request, isadmin=False)

    # 获取文件之前 先清理一下1天之前的文件
    # 获取当前时间
    now = timezone.now()

    # 计算一天前的时间
    one_day_ago = now - timedelta(days=1)

    # 查询created_at字段在一天之前的数据并删除
    del_all_chatfiles = ChatFiles.objects.filter(created_at__lte=one_day_ago)

    # 创建FileSystemStorage实例
    storage = FileSystemStorage()

    # 先删除文件
    for del_chatfiles_obj in del_all_chatfiles:
        file_name_path = del_chatfiles_obj.img

        # 删除文件
        try:
            storage.delete(str(file_name_path))
        except:
            pass

    # 删除完文件后 就删除数据库里面的数据
    try:
        del_all_chatfiles.delete()
    except:
        pass


    all_chatfiles =  ChatFiles.objects.filter(user_id=userid, avatar=False)

    json_data_str = serialize('json', all_chatfiles)
    json_data = json.loads(json_data_str)

    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        json_data[i]['fields']['created_at'] = created_at_second

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def upload_remove(request):
    '''
    删除文件
    '''
    # 获取用户id
    userid = get_login_user_id(request, isadmin=False)

    file_id = request.GET.get('id', None)


    if not file_id:
        res_mes = {
            "code": 1,
            "data": "非法参数或参数解析失败"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    try:
        del_obj = ChatFiles.objects.filter(user_id=userid, id=file_id)
        file_name_path = del_obj[0].img
        if not del_obj:
            res_mes = {
                "code": 1,
                "data": "file not existed"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
    except:
        res_mes = {
            "code": 1,
            "data": "file not existed"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    # 创建FileSystemStorage实例
    storage = FileSystemStorage()

    # 删除文件
    try:
        res = storage.delete(str(file_name_path))
    except:
        res_mes = {
            "code": 1,
            "data": "删除文件失败!"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    
    try:
        del_obj.delete()
    except:
        res_mes = {
            "code": 1,
            "data": "删除文件数据库失败!"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

    if res is None or res:
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    else:
        res_mes = {
            "code": 1,
            "data": "failed to update database"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

